package com.jee.ssm.common.utils;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.audience.AudienceTarget;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;

import com.jee.ssm.common.config.Logger;
import com.jee.ssm.model.PersonalMessage;

import java.util.List;

public class PushUtils {

    public static final String secret = "0d8adf2b7918c55e4ae053cb";

    public static final String appKey = "a8abad449b25a963b810e436";

    public static void pushPersonalMessage(List<PersonalMessage> list) {
        try {
            JPushClient jpushClient = new JPushClient(secret, appKey, null, ClientConfig.getInstance());
            for(PersonalMessage pm : list) {
            	
            	push_message_to_android(jpushClient, pm);
            	
            	push_message_to_ios(jpushClient, pm);
            	
            }
            Thread.sleep(5000);
            // 请求结束后，调用 NettyHttpClient 中的 close 方法，否则进程不会退出。
            jpushClient.close();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
    
    public static void push_message_to_android(JPushClient jpushClient, PersonalMessage pm) {
    	try {
            PushPayload payload = buildPushObject_all_alias_alert_android(pm.getUserId(), pm.getTitle(), pm.getContent());
            PushResult result = jpushClient.sendPush(payload);
            Logger.info("Got result - " + result);
        } catch (APIConnectionException e) {
            Logger.error("Connection error, should retry later", e);
        } catch (APIRequestException e) {
            Logger.error("Should review the error, and fix the request", e);
            Logger.info("HTTP Status: " + e.getStatus());
            Logger.info("Error Code: " + e.getErrorCode());
            Logger.info("Error Message: " + e.getErrorMessage());
        }
    }
    
    public static void push_message_to_ios(JPushClient jpushClient, PersonalMessage pm) {
        try {
            PushPayload payload = buildPushObject_all_alias_alert_ios(pm.getUserId(), pm.getTitle(), pm.getContent());
            PushResult result = jpushClient.sendPush(payload);
            Logger.info("Got result - " + result);
        } catch (APIConnectionException e) {
            Logger.error("Connection error, should retry later", e);
        } catch (APIRequestException e) {
            Logger.error("Should review the error, and fix the request", e);
            Logger.info("HTTP Status: " + e.getStatus());
            Logger.info("Error Code: " + e.getErrorCode());
            Logger.info("Error Message: " + e.getErrorMessage());
        }
    }

    public static void pushPersonalMessageToOne(PersonalMessage pm)throws Exception{
        try {
            JPushClient jpushClient = new JPushClient(secret, appKey, null, ClientConfig.getInstance());
//            try {
                PushPayload payload = buildPushObject_all_alias_alert_android(pm.getUserId(), pm.getTitle(), pm.getContent());
//                PushPayload payload2 = buildPushObject_ios_audienceMore_messageWithExtras(pm.getUserId(), pm.getTitle(), pm.getContent());
                PushResult result = jpushClient.sendPush(payload);
                Logger.info("Got result - " + result);
//                PushResult result2 = jpushClient.sendPush(payload2);
//                  Logger.info("Got result - " + result2);
//            } catch (APIConnectionException e) {
//                Logger.error("Connection error, should retry later", e);
//            } catch (APIRequestException e) {
//                e.printStackTrace();
                /*Logger.error("Should review the error, and fix the request", e);
                Logger.info("HTTP Status: " + e.getStatus());
                Logger.info("Error Code: " + e.getErrorCode());
                Logger.info("Error Message: " + e.getErrorMessage());*/
//            }

            Thread.sleep(5000);
            // 请求结束后，调用 NettyHttpClient 中的 close 方法，否则进程不会退出。
            jpushClient.close();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }


    public static void pushPersonalMessageToOneIos(PersonalMessage pm) throws Exception{

//        try {
            JPushClient jpushClient = new JPushClient(secret, appKey, null, ClientConfig.getInstance());
//            try {
                PushPayload payload = buildPushObject_all_alias_alert_ios(pm.getUserId(), pm.getTitle(), pm.getContent());
                PushResult result = jpushClient.sendPush(payload);
                Logger.info("Got result IOS - " + result);
//            } catch (APIConnectionException e) {
//                Logger.error("Connection error, should retry later", e);
//            } catch (APIRequestException e) {
//                e.printStackTrace();
                /*Logger.error("Should review the error, and fix the request", e);
                Logger.info("HTTP Status: " + e.getStatus());
                Logger.info("Error Code: " + e.getErrorCode());
                Logger.info("Error Message: " + e.getErrorMessage());*/
//            }

            Thread.sleep(5000);
            // 请求结束后，调用 NettyHttpClient 中的 close 方法，否则进程不会退出。
            jpushClient.close();
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }

    }


    public static PushPayload buildPushObject_all_alias_alert_android(String id, String title, String content) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.all())
                .setAudience(Audience.alias(id))
                .setNotification(Notification.android(content, title, null))
                .build();
    }
    
    public static PushPayload buildPushObject_all_alias_alert_ios(String id, String title, String content) {
//    	return PushPayload.newBuilder().setPlatform(Platform.all()).setAudience(Audience.alias(id)).setNotification(Notification.ios(title, null)).build();

        return PushPayload.newBuilder()
                .setPlatform(Platform.ios())
                .setAudience(Audience.alias(id))
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(IosNotification.newBuilder()
                                .setAlert(title)
                                .setBadge(5)
                                .setSound("happy")
                                .addExtra("from", "JPush")
                                .build())
                        .build())
                .setMessage(Message.content(content))
                .setOptions(Options.newBuilder()
                        .setApnsProduction(false)
                        .build())
                .build();

    }
    
    public static PushPayload buildPushObject_ios_audienceMore_messageWithExtras(String id, String title, String content) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.newBuilder()
                        .addAudienceTarget(AudienceTarget.tag("tag1", "tag2"))
                        .addAudienceTarget(AudienceTarget.alias("alias1", "alias2"))
                        .build())
                .setMessage(Message.newBuilder()
                        .setMsgContent(content)
                        .addExtra("from", "JPush")
                        .build())
                .build();
    }

    public static void pushSystemMessage(String title) {
        try {
            JPushClient jpushClient = new JPushClient(secret, appKey, null, ClientConfig.getInstance());

            try {
                PushPayload payload = buildPushObject_all_all_alert(title);
                PushResult result = jpushClient.sendPush(payload);
                Logger.info("Got result - " + result);
            } catch (APIConnectionException e) {
                Logger.error("Connection error, should retry later", e);
            } catch (APIRequestException e) {
                Logger.error("Should review the error, and fix the request", e);
                Logger.info("HTTP Status: " + e.getStatus());
                Logger.info("Error Code: " + e.getErrorCode());
                Logger.info("Error Message: " + e.getErrorMessage());
            }

            Thread.sleep(5000);
            // 请求结束后，调用 NettyHttpClient 中的 close 方法，否则进程不会退出。
            jpushClient.close();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

    public static PushPayload buildPushObject_all_all_alert(String content) {
        return PushPayload.alertAll(content);
    }

}
